package com.inbound;

import com.object.Gprs;
import com.NettyServer;
import com.util.ProtocolUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;


public class RegisterHandler extends ChannelInboundHandlerAdapter{
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg){
        if (doRegister(ctx, msg)) {
            ctx.pipeline().remove("Register"); // register only once;
            ctx.fireChannelRead(msg);
        }
        else
            ctx.close();
    }



    /**
     * Instrument register
     * This method does not modify readerIndex or writerIndex of this buffer.
     * @param ctx
     * @param msg
     * @return
     */
    private boolean doRegister(ChannelHandlerContext ctx, Object msg){
        // Instruments verify to register
        String gprsId = ProtocolUtil.getGprsId((ByteBuf)msg);
        if (gprsId == null)
            return false;
        else {
            Gprs gprs = new Gprs(gprsId, ctx);
            gprs.online();
            ctx.channel().attr(NettyServer.GPRS).set(gprs); // bind this channel GPRS attribute with gprs_id
            
            NettyServer.GPRS_MAP.put(gprsId, gprs);
            return true;
        }
    }
}
